<template>
  <div class="login">
    <div class="login-form">
      <div class="login-header">
        <img class="logo" src="@/assets/images/logo-black.png" alt="" />
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="账号登录" :name="1">
          <el-form
            ref="formRef"
            :hide-required-asterisk="true"
            :model="form"
            :rules="rules"
            :label-width="80"
            label-position="top"
            size="large"
          >
            <div class="form-main">
              <el-form-item label="" prop="userName">
                <el-input placeholder="请输入用户名" clearable v-model="form.userName" />
              </el-form-item>
              <el-form-item label="" prop="password">
                <el-input type="password" placeholder="请输入密码" clearable v-model="form.password" />
              </el-form-item>
              <el-form-item label="" prop="remember" class="remember-box">
                <el-checkbox label="记住密码" v-model="form.remember" />
              </el-form-item>
            </div>
            <el-form-item>
              <el-button class="login-btn" type="primary" @click="submitForm(formRef)"> 登录 </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="验证码登录" :name="2">
          <el-form
            ref="formRef2"
            :hide-required-asterisk="true"
            :model="form2"
            :rules="rules2"
            :label-width="80"
            label-position="top"
            size="large"
          >
            <div class="form-main">
              <el-form-item label="" prop="phone">
                <el-input v-model="form2.phone" clearable placeholder="请输入手机号">
                  <template #prepend>
                    <el-select filterable v-model="form2.areaCode" placeholder="请选择" style="width: 110px">
                      <el-option v-for="(item, index) in areaCodeList" :key="index" :label="item.label" :value="item.value" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="" prop="code">
                <el-input v-model="form2.code" clearable placeholder="请输入验证码">
                  <template #append>
                    <el-button style="width: 110px" :disabled="count !== 60" @click="handleSendCode">{{
                      count === 60 ? '发送验证码' : `${count}s`
                    }}</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button class="login-btn" type="primary" @click="submitForm(formRef2)"> 登录 </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { loginApi, sendCodeApi } from './apis'
import { areaCodeList } from './constant'

const activeName = ref(1)

// 账号登录
const remember = JSON.parse(localStorage.getItem('remember') || '{}')
const form = reactive({
  userName: remember.userName || '',
  password: remember.password || '',
  remember: true
})
const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 验证码登录
const form2 = reactive({
  areaCode: areaCodeList[0].value,
  phone: '',
  code: ''
})
const rules2 = {
  areaCode: [{ required: true, message: '请选择区号', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { required: true, pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// 调用登录接口
const handleLogin = () => {
  const params: any = {
    loginType: activeName.value,
    password: form.password,
    account: form.userName,
    smsCode: form2.code,
    mobile: `${form2.areaCode}@${form2.phone}`
  }
  loginApi(params).then((res) => {
    ElMessage.success('登录成功')
    // 存储token
    localStorage.setItem('token', res.accessToken)
    // 存储记住密码
    localStorage.setItem(
      'remember',
      form.remember
        ? JSON.stringify({
            userName: form.userName,
            password: form.password
          })
        : ''
    )
    // 存储用户信息
    localStorage.setItem('userInfo', JSON.stringify(res.loginInfo))
    // 存储权限列表
    localStorage.setItem('authList', JSON.stringify(res.rolePrivileges))
    // 记录上次退出时url
    const preRoutePath = localStorage.getItem('preRoutePath')
    router.push(preRoutePath || '/')
  })
}

// 提交登录
const router = useRouter()
const formRef = ref()
const formRef2 = ref()
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid: boolean) => {
    if (valid) {
      handleLogin()
    }
  })
}

// 发送验证码
const count = ref(60)
const handleSendCode = async () => {
  // 先校验是否填写了手机号
  try {
    await formRef2.value.validateField('phone')
  } catch (error) {
    return
  }
  // 倒计时过程中禁止点击按钮
  if (count.value !== 60) {
    return
  }
  const params = { mobile: `${form2.areaCode}@${form2.phone}` }
  sendCodeApi(params).then(() => {
    // 倒计时
    count.value = 59
    let timer: any = setInterval(() => {
      count.value--
      if (!count.value) {
        clearInterval(timer)
        timer = null
        count.value = 60
      }
    }, 1000)
  })
}
</script>

<style lang="less" scoped>
.login {
  position: relative;
  height: 100vh;
  background: url('@/assets/images/login-bg.png') no-repeat center;
  background-size: cover;
  .remember-box {
    margin-top: -16px;
  }
  :deep(.el-tabs__nav-scroll) {
    display: flex;
    justify-content: center;
    .el-tabs__item {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .logo {
    width: 300px;
  }
  .login-header {
    text-align: center;
    margin-bottom: 40px;
  }
  .login-form {
    width: 400px;
    padding: 40px 30px;
    border-radius: 5px;
    position: absolute;
    left: 50%;
    top: 10%;
    transform: translate(-50%);
    .form-main {
      padding-top: 8px;
      height: 170px;
    }
  }
  .login-btn {
    width: 100%;
  }
}
</style>
